Passed
Pull Request — master (#100)
by Kiran
04:43
created

$(ꞌ.wpi-gd-package .submitdeleteꞌ).click   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
jQuery(function($) {
2
    //'use strict';
3
4
    // Tooltips
5
    $('.wpi-help-tip').tooltip({
6
        content: function() {
7
            return $(this).prop('title');
8
        },
9
        tooltipClass: 'wpi-ui-tooltip',
10
        position: {
11
            my: 'center top',
12
            at: 'center bottom+10',
13
            collision: 'flipfit'
14
        },
15
        hide: {
16
            duration: 200
17
        },
18
        show: {
19
            duration: 200
20
        }
21
    });
22
23
    var wpiGlobalTax = WPInv_Admin.tax != 0 ? WPInv_Admin.tax : 0;
0 ignored issues
show
Unused Code introduced by
The variable wpiGlobalTax seems to be never used. Consider removing it.
Loading history...
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
24
    var wpiGlobalDiscount = WPInv_Admin.discount != 0 ? WPInv_Admin.discount : 0;
0 ignored issues
show
Unused Code introduced by
The variable wpiGlobalDiscount seems to be never used. Consider removing it.
Loading history...
25
    var wpiSymbol = WPInv_Admin.currency_symbol;
26
    var wpiPosition = WPInv_Admin.currency_pos;
27
    var wpiThousandSep = WPInv_Admin.thousand_sep;
28
    var wpiDecimalSep = WPInv_Admin.decimal_sep;
29
    var wpiDecimals = WPInv_Admin.decimals;
30
    var $postForm = $('.post-type-wpi_invoice form#post');
31
    if ($('[name="wpinv_status"]', $postForm).length) {
32
        var origStatus = $('[name="wpinv_status"]', $postForm).val();
33
        $('[name="original_post_status"]', $postForm).val(origStatus);
34
        $('[name="hidden_post_status"]', $postForm).val(origStatus);
35
        $('[name="post_status"]', $postForm).replaceWith('<input type="hidden" value="' + origStatus + '" id="post_status" name="post_status">');
36
        $postForm.on('change', '[name="wpinv_status"]', function(e) {
37
            e.preventDefault();
38
            $('[name="post_status"]', $postForm).replaceWith('<input type="hidden" value="' + $(this).val() + '" id="post_status" name="post_status">');
39
        });
40
    }
41
    $('input.wpi-price').on("contextmenu", function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
42
        return false;
43
    });
44
    $(document).on('keypress', 'input.wpi-price', function(e) {
45
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
46
        if ($.inArray(e.key, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", "."]) !== -1) {
47
            return true;
48
        } else if (e.ctrlKey || e.shiftKey) {
49
            return false;
50
        } else if ($.inArray(key, [8, 35, 36, 37, 39, 46]) !== -1) {
51
            return true;
52
        }
53
        return false;
54
    });
55
    // sorts out the number to enable calculations
56
    function wpinvRawNumber(x) {
0 ignored issues
show
introduced by
The function wpinvRawNumber does not seem to be used and can be removed.
Loading history...
57
        // removes the thousand seperator
58
        var parts = x.toString().split(wpiThousandSep);
59
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, '');
60
        var amount = parts.join('');
61
        // makes the decimal seperator a period
62
        var output = amount.toString().replace(/\,/g, '.');
63
        output = parseFloat(output);
64
        if (isNaN(output)) {
65
            output = 0;
66
        }
67
        if (output && output < 0) {
68
            output = output * (-1);
69
        }
70
        return output;
71
    }
72
    // formats number into users format
73
    function wpinvFormatNumber(nStr) {
74
        var num = nStr.split('.');
75
        var x1 = num[0];
76
        var x2 = num.length > 1 ? wpiDecimalSep + num[1] : '';
77
        var rgx = /(\d+)(\d{3})/;
78
        while (rgx.test(x1)) {
79
            x1 = x1.replace(rgx, '$1' + wpiThousandSep + '$2');
80
        }
81
        return x1 + x2;
82
    }
83
    // format the amounts
84
    function wpinvFormatAmount(amount) {
0 ignored issues
show
introduced by
The function wpinvFormatAmount does not seem to be used and can be removed.
Loading history...
85
        if (typeof amount !== 'number') {
86
            amount = parseFloat(amount);
87
        }
88
        // do the symbol position formatting   
89
        var formatted = 0;
90
        var amount = amount.toFixed(wpiDecimals);
91
        switch (wpiPosition) {
92
            case 'left':
93
                formatted = wpiSymbol + wpinvFormatNumber(amount);
94
                break;
95
            case 'right':
96
                formatted = wpinvFormatNumber(amount) + wpiSymbol;
97
                break;
98
            case 'left_space':
99
                formatted = wpiSymbol + ' ' + wpinvFormatNumber(amount);
100
                break;
101
            case 'right_space':
102
                formatted = wpinvFormatNumber(amount) + ' ' + wpiSymbol;
103
                break;
104
            default:
105
                formatted = wpiSymbol + wpinvFormatNumber(amount);
106
                break;
107
        }
108
        return formatted;
109
    }
110
    /**
111
     * Invoice Notes Panel
112
     */
113
    var wpinv_meta_boxes_notes = {
114
        init: function() {
115
            $('#wpinv-notes')
116
                .on('click', 'a.add_note', this.add_invoice_note)
117
                .on('click', 'a.delete_note', this.delete_invoice_note);
118
            if ($('ul.invoice_notes')[0]) {
119
                $('ul.invoice_notes')[0].scrollTop = $('ul.invoice_notes')[0].scrollHeight;
120
            }
121
        },
122
        add_invoice_note: function() {
123
            if (!$('textarea#add_invoice_note').val()) {
124
                return;
125
            }
126
            $('#wpinv-notes').block({
127
                message: null,
128
                overlayCSS: {
129
                    background: '#fff',
130
                    opacity: 0.6
131
                }
132
            });
133
            var data = {
134
                action: 'wpinv_add_note',
135
                post_id: WPInv_Admin.post_ID,
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
136
                note: $('textarea#add_invoice_note').val(),
137
                note_type: $('select#invoice_note_type').val(),
138
                _nonce: WPInv_Admin.add_invoice_note_nonce
139
            };
140
            $.post(WPInv_Admin.ajax_url, data, function(response) {
141
                $('ul.invoice_notes').append(response);
142
                $('ul.invoice_notes')[0].scrollTop = $('ul.invoice_notes')[0].scrollHeight;
143
                $('#wpinv-notes').unblock();
144
                $('#add_invoice_note').val('');
145
            });
146
            return false;
147
        },
148
        delete_invoice_note: function() {
149
            var note = $(this).closest('li.note');
150
            $(note).block({
151
                message: null,
152
                overlayCSS: {
153
                    background: '#fff',
154
                    opacity: 0.6
155
                }
156
            });
157
            var data = {
158
                action: 'wpinv_delete_note',
159
                note_id: $(note).attr('rel'),
160
                _nonce: WPInv_Admin.delete_invoice_note_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
161
            };
162
            $.post(WPInv_Admin.ajax_url, data, function() {
163
                $(note).remove();
164
            });
165
            return false;
166
        }
167
    };
168
    wpinv_meta_boxes_notes.init();
169
    $('.post-type-wpi_invoice [name="post"] #submitpost [type="submit"]').on('click', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
170
        if (parseInt($(document.body).find('.wpinv-line-items > .item').length) < 1) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if parseInt($(document.body...s > .item").length) < 1 is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
171
            alert(WPInv_Admin.emptyInvoice);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
172
            $('#wpinv_invoice_item').focus();
173
            return false;
174
        }
175
    });
176
    var invDetails = jQuery('#gdmbx2-metabox-wpinv_details').html();
177
    if (invDetails) {
178
        jQuery('#submitpost', jQuery('.wpinv')).detach().appendTo(jQuery('#wpinv-details'));
179
        jQuery('#submitdiv', jQuery('.wpinv')).hide();
180
        jQuery('#major-publishing-actions', '#wpinv-details').find('input[type=submit]').attr('name', 'save_invoice').val(WPInv_Admin.save_invoice);
181
    }
182
    var invBilling = jQuery('#wpinv-address.postbox').html();
183
    if (invBilling) {
184
        jQuery('#post_author_override', '#authordiv').remove(); //.addClass('gdmbx2-text-medium').detach().prependTo(jQuery('.gdmbx-customer-div'));
185
        jQuery('#authordiv', jQuery('.wpinv')).hide();
186
    }
187
    var wpinvNumber;
188
    if (!jQuery('#post input[name="post_title"]').val() && (wpinvNumber = jQuery('#wpinv-details input[name="wpinv_number"]').val())) {
189
        jQuery('#post input[name="post_title"]').val(wpinvNumber);
190
    }
191
    var wpi_stat_links = jQuery('.post-type-wpi_invoice .subsubsub');
192
    if (wpi_stat_links.is(':visible')) {
193
        var publish_count = jQuery('.publish', wpi_stat_links).find('.count').text();
194
        jQuery('.publish', wpi_stat_links).find('a').html(WPInv_Admin.status_publish + ' <span class="count">' + publish_count + '</span>');
195
        var pending_count = jQuery('.wpi-pending', wpi_stat_links).find('.count').text();
196
        jQuery('.pending', wpi_stat_links).find('a').html(WPInv_Admin.status_pending + ' <span class="count">' + pending_count + '</span>');
197
    }
198
    // Update tax rate state field based on selected rate country
199
    $(document.body).on('change', '#wpinv_tax_rates select.wpinv-tax-country', function() {
200
        var $this = $(this);
201
        data = {
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.data.
Loading history...
202
            action: 'wpinv_get_states_field',
203
            country: $(this).val(),
204
            field_name: $this.attr('name').replace('country', 'state')
205
        };
206
        $.post(ajaxurl, data, function(response) {
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
207
            if ('nostates' == response) {
208
                var text_field = '<input type="text" name="' + data.field_name + '" value=""/>';
209
                $this.parent().next().find('select').replaceWith(text_field);
210
            } else {
211
                $this.parent().next().find('input,select').show();
212
                $this.parent().next().find('input,select').replaceWith(response);
213
            }
214
        });
215
        return false;
216
    });
217
    // Insert new tax rate row
218
    $('#wpinv_add_tax_rate').on('click', function() {
219
        var row = $('#wpinv_tax_rates tbody tr:last');
220
        var clone = row.clone();
221
        var count = row.parent().find('tr').length;
222
        clone.find('td input').not(':input[type=checkbox]').val('');
223
        clone.find('td [type="checkbox"]').attr('checked', false);
224
        clone.find('input, select').each(function() {
225
            var name = $(this).attr('name');
226
            name = name.replace(/\[(\d+)\]/, '[' + parseInt(count) + ']');
227
            $(this).attr('name', name).attr('id', name);
228
        });
229
        clone.find('label').each(function() {
230
            var name = $(this).attr('for');
231
            name = name.replace(/\[(\d+)\]/, '[' + parseInt(count) + ']');
232
            $(this).attr('for', name);
233
        });
234
        clone.insertAfter(row);
235
        return false;
236
    });
237
    // Remove tax row
238
    $(document.body).on('click', '#wpinv_tax_rates .wpinv_remove_tax_rate', function() {
239
        var tax_rates = $('#wpinv_tax_rates tbody tr:visible');
240
        var count = tax_rates.length;
241
        if (count === 1) {
242
            $('#wpinv_tax_rates select').val('');
243
            $('#wpinv_tax_rates input[type="text"]').val('');
244
            $('#wpinv_tax_rates input[type="number"]').val('');
245
            $('#wpinv_tax_rates input[type="checkbox"]').attr('checked', false);
246
        } else {
247
            $(this).closest('tr').remove();
248
        }
249
        /* re-index after deleting */
250
        $('#wpinv_tax_rates tbody tr').each(function(rowIndex) {
251
            $(this).children().find('input, select').each(function() {
252
                var name = $(this).attr('name');
253
                name = name.replace(/\[(\d+)\]/, '[' + (rowIndex) + ']');
254
                $(this).attr('name', name).attr('id', name);
255
            });
256
        });
257
        return false;
258
    });
259
    var elB = $('#wpinv-address');
260
    $('#wpinv_country', elB).change(function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
261
        var $this = $(this);
262
        data = {
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.data.
Loading history...
263
            action: 'wpinv_get_states_field',
264
            country: $(this).val(),
265
            field_name: 'wpinv_state',
266
        };
267
        $this.closest('.gdmbx-row').find('.wpi-loader').show();
268
        $('#wpinv_state', elB).css({
269
            'opacity': '.5'
270
        });
271
        $.post(ajaxurl, data, function(response) {
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
272
            var selected = typeof $this.data('state') !== 'undefined' ? $this.data('state') : "";
273
            if ('nostates' === response) {
274
                var text_field = '<input type="text" value="' + selected + '" id="wpinv_state" name="wpinv_state" />';
275
                $('#wpinv_state', elB).replaceWith(text_field);
276
            } else {
277
                $('#wpinv_state', elB).replaceWith(response);
278
                $('#wpinv_state', elB).find('option[value="' + selected + '"]').attr('selected', 'selected');
279
                $('#wpinv_state', elB).find('option[value=""]').remove();
280
            }
281
            $('#wpinv_state', elB).addClass('gdmbx2-text-large');
282
            if (typeof $this.data('change') === '1') {
283
                $('#wpinv_state', elB).change();
284
            } else {
285
                window.wpiConfirmed = true;
286
                $('#wpinv-recalc-totals').click();
287
                window.wpiConfirmed = false;
288
            }
289
            $this.closest('.gdmbx-row').find('.wpi-loader').hide();
290
            $('#wpinv_state', elB).css({
291
                'opacity': '1'
292
            });
293
        });
294
        return false;
295
    });
296
    $('#wpinv_state', elB).live('change', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
297
        window.wpiConfirmed = true;
298
        $('#wpinv-recalc-totals').click();
299
        window.wpiConfirmed = false;
300
    });
301
    $('#wpinv-fill-user-details').click(function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
302
        var metaBox = $(this).closest('.inside');
303
        var user_id = $('select[name="post_author_override"]', metaBox).val();
304
        if (!user_id || $(this).attr('disabled')) {
305
            return false;
306
        }
307
        if (window.confirm(WPInv_Admin.FillBillingDetails)) {
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Complexity Best Practice introduced by
There is no return statement if window.confirm(WPInv_Admin.FillBillingDetails) is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
308
            var data = {
309
                action: 'wpinv_get_billing_details',
310
                user_id: user_id,
311
                _nonce: WPInv_Admin.billing_details_nonce
312
            };
313
            wpinvBlock(metaBox);
314
            $.post(WPInv_Admin.ajax_url, data, function(response) {
315
                var elCountry = $('#wpinv_country', metaBox);
316
                elCountry.removeAttr('data-state').removeAttr('data-change');
317
                if (response && typeof response == 'object') {
318
                    if (response.success === true && typeof response.data.billing_details == 'object') {
319
                        var state = false;
320
                        var country = false;
321
                        $.each(response.data.billing_details, function(key, value) {
322
                            if (key == 'state') {
323
                                state = value;
324
                            } else if (key == 'country') {
325
                                country = value;
326
                            } else {
327
                                $('#wpinv_' + key, metaBox).val(value).change();
328
                            }
329
                        });
330
                        if (country !== false) {
331
                            if (state !== false) {
332
                                elCountry.data('state', state).data('change', '1');
333
                            }
334
                            elCountry.val(country).change();
335
                        }
336
                    }
337
                }
338
                wpinvUnblock(metaBox);
339
            });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
340
        }
341
    });
342
    var WPInv = {
343
        init: function() {
344
            this.preSetup();
345
            this.prices();
346
            this.remove_item();
347
            this.add_item();
348
            this.recalculateTotals();
349
            this.setup_tools();
350
        },
351
        preSetup: function() {
352
            $('.wpiDatepicker').each(function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
353
                var $this = $(this);
354
                var args = {};
355
                if ($this.attr('data-changeMonth')) {
356
                    args.changeMonth = true;
357
                }
358
                if ($this.attr('data-changeYear')) {
359
                    args.changeYear = true;
360
                }
361
                if ($this.attr('data-dateFormat')) {
362
                    args.dateFormat = $this.attr('data-dateformat');
363
                }
364
                if ($this.attr('data-minDate')) {
365
                    args.minDate = $this.attr('data-minDate');
366
                }
367
                $(this).datepicker(args);
368
            });
369
            var wpinvColorPicker = $('.wpinv-color-picker');
370
            if (wpinvColorPicker.length) {
371
                wpinvColorPicker.wpColorPicker();
372
            }
373
            var no_states = $('select.wpinv-no-states');
374
            if (no_states.length) {
375
                no_states.closest('tr').hide();
376
            }
377
            // Update base state field based on selected base country
378
            $('select[name="wpinv_settings[default_country]"]').change(function() {
379
                var $this = $(this),
380
                    $tr = $this.closest('tr');
381
                data = {
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.data.
Loading history...
382
                    action: 'wpinv_get_states_field',
383
                    country: $(this).val(),
384
                    field_name: 'wpinv_settings[default_state]'
385
                };
386
                $.post(ajaxurl, data, function(response) {
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
387
                    if ('nostates' == response) {
388
                        $tr.next().hide();
389
                    } else {
390
                        $tr.next().show();
391
                        $tr.next().find('select').replaceWith(response);
392
                    }
393
                });
394
                return false;
395
            });
396
            $('#wpinv-address').on('click', '.wpinv-new-user', function(e) {
397
                e.preventDefault();
398
                var mBox = $('#wpinv-address');
399
                $(this).hide();
400
                $('#wpinv-fill-user-details', elB).attr('disabled', true);
401
                $('.wpinv-new-cancel', mBox).show();
402
                $('#wpinv_new_user', mBox).val(1);
403
                $('#wpinv_email', mBox).prop('required', 'required');
404
                $('.gdmbx-wpinv-user-id', mBox).hide();
405
                $('.gdmbx-wpinv-email', mBox).show();
406
            });
407
            $('#wpinv-address').on('click', '.wpinv-new-cancel', function(e) {
408
                e.preventDefault();
409
                var mBox = $('#wpinv-address');
410
                $(this).hide();
411
                $('#wpinv-fill-user-details', elB).attr('disabled', false);
412
                $('.wpinv-new-user', mBox).show();
413
                $('#wpinv_new_user', mBox).val(0);
414
                $('#wpinv_email', mBox).prop('required', false);
415
                $('.gdmbx-wpinv-email', mBox).hide();
416
                $('.gdmbx-wpinv-user-id', mBox).show();
417
            });
418
            $('#wpinv-address #wpinv_email').live('change', function(e) {
419
                var metaBox = $(this).closest('.inside');
420
                if (parseInt($('#wpinv_new_user', metaBox).val()) != 1) {
421
                    return false;
422
                }
423
                e.preventDefault();
424
                wpinvBlock(metaBox);
425
                var data = {
426
                    action: 'wpinv_check_email',
427
                    email: $(this).val(),
428
                    _nonce: WPInv_Admin.wpinv_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
429
                };
430
                $.post(WPInv_Admin.ajax_url, data, function(response) {
431
                    var elCountry = $('#wpinv_country', metaBox);
432
                    elCountry.removeAttr('data-state').removeAttr('data-change');
433
                    if (response && typeof response == 'object') {
434
                        if (response.success === true && typeof response.data.billing_details == 'object') {
435
                            if (!$('#post_author_override [value="' + response.data.id + '"]', metaBox).val()) {
436
                                $('#post_author_override', metaBox).prepend('<option value="' + response.data.id + '">' + response.data.name + '</option>');
437
                            }
438
                            $('#post_author_override', metaBox).val(response.data.id);
439
                            $('.wpinv-new-cancel', metaBox).click();
440
                            var state = false;
441
                            var country = false;
442
                            $.each(response.data.billing_details, function(key, value) {
443
                                if (key == 'state') {
444
                                    state = value;
445
                                } else if (key == 'country') {
446
                                    country = value;
447
                                } else {
448
                                    if (key != 'email') {
449
                                        $('#wpinv_' + key, metaBox).val(value).change();
450
                                    }
451
                                }
452
                            });
453
                            if (country !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
454
                                if (state !== false) {
455
                                    elCountry.data('state', state).data('change', '1');
456
                                }
457
                                elCountry.val(country).change();
458
                            }
459
                        }
460
                    }
461
                    wpinvUnblock(metaBox);
462
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
463
            });
464
            $('#wpinv_discount_type').live('change', function(e) {
465
                e.preventDefault();
466
                var mBox = $(this).closest('.inside');
467
                if ($(this).val() == 'flat') {
468
                    $('.wpi-discount-p', mBox).hide();
469
                    $('.wpi-discount-f', mBox).show();
470
                } else {
471
                    $('.wpi-discount-p', mBox).show();
472
                    $('.wpi-discount-f', mBox).hide();
473
                }
474
            });
475
            $('#wpinv_discount_type').trigger('change');
476
            
477
            $('#wpinv-apply-code').live('click', function(e) {
478
                e.preventDefault();
479
                var $this = $(this);
480
                var $form = $(this).closest('form[name="post"]');
481
                var invoice_id = parseInt($form.find('input#post_ID').val());
482
                if (!invoice_id > 0) {
483
                    return false;
484
                }
485
                
486
                if (!parseInt($(document.body).find('.wpinv-line-items > .item').length) > 0) {
487
                    alert(WPInv_Admin.emptyInvoice);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
488
                    $('#wpinv_invoice_item').focus();
489
                    return false;
490
                }
491
                
492
                var discount_code = $('#wpinv_discount', $form).val();
493
                
494
                if (!discount_code) {
495
                    $('#wpinv_discount', $form).focus();
496
                    return false;
497
                }
498
                
499
                $this.attr('disabled', true);
500
                $this.after('<span class="wpi-refresh">&nbsp;&nbsp;<i class="fa fa-spin fa-refresh"></i></span>');
501
502
                var data = {
503
                    action: 'wpinv_admin_apply_discount',
504
                    invoice_id: invoice_id,
505
                    code: discount_code,
506
                    _nonce: WPInv_Admin.wpinv_nonce
507
                };
508
                
509
                $.post(WPInv_Admin.ajax_url, data, function(response) {
510
                    var msg, success;
511
                    if (response && typeof response == 'object') {
512
                        if (response.success === true) {
513
                            success = true;
514
                            
515
                            $('#wpinv_discount', $form).attr('readonly', true);
516
                            $this.removeClass('wpi-inlineb').addClass('wpi-hide');
517
                            $('#wpinv-remove-code', $form).removeClass('wpi-hide').addClass('wpi-inlineb');
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
518
                        }
519
                        
520
                        if (response.msg) {
521
                            msg = response.msg;
522
                        }
523
                    }
524
                    
525
                    $this.attr('disabled', false);
526
                    $this.closest('div').find('.wpi-refresh').remove();
527
                    
528
                    if (success) {
529
                        console.log(success);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
530
                        window.wpiConfirmed = true;
531
                        $('#wpinv-recalc-totals').click();
532
                        window.wpiConfirmed = false;
533
                    }
534
                    
535
                    if (msg) {
536
                        alert(msg);
537
                    }
538
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
539
            });
540
            
541
            $('#wpinv-remove-code').live('click', function(e) {
542
                e.preventDefault();
543
                var $this = $(this);
544
                var $form = $(this).closest('form[name="post"]');
545
                var invoice_id = parseInt($form.find('input#post_ID').val());
546
                var discount_code = $('#wpinv_discount', $form).val();
547
                if (!invoice_id > 0) {
548
                    return false;
549
                }
550
                
551
                if (!invoice_id > 0 || !parseInt($(document.body).find('.wpinv-line-items > .item').length) > 0 || !discount_code) {
552
                    $this.removeClass('wpi-inlineb').addClass('wpi-hide');
553
                    $('#wpinv_discount', $form).attr('readonly', false).val('');
554
                    $('#wpinv-apply-code', $form).removeClass('wpi-hide').addClass('wpi-inlineb');
555
                    return false;
556
                }
557
                
558
                $this.attr('disabled', true);
559
                $this.after('<span class="wpi-refresh">&nbsp;&nbsp;<i class="fa fa-spin fa-refresh"></i></span>');
560
561
                var data = {
562
                    action: 'wpinv_admin_remove_discount',
563
                    invoice_id: invoice_id,
564
                    code: discount_code,
565
                    _nonce: WPInv_Admin.wpinv_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
566
                };
567
                
568
                $.post(WPInv_Admin.ajax_url, data, function(response) {
569
                    var msg, success;
570
                    if (response && typeof response == 'object') {
571
                        if (response.success === true) {
572
                            success = true;
573
                            
574
                            $this.removeClass('wpi-inlineb').addClass('wpi-hide');
575
                            $('#wpinv_discount', $form).attr('readonly', false).val('');
576
                            $('#wpinv-apply-code', $form).removeClass('wpi-hide').addClass('wpi-inlineb');
577
                        }
578
                        
579
                        if (response.msg) {
580
                            msg = response.msg;
581
                        }
582
                    }
583
                    
584
                    $this.attr('disabled', false);
585
                    $this.closest('div').find('.wpi-refresh').remove();
586
                    
587
                    if (success) {
588
                        window.wpiConfirmed = true;
589
                        $('#wpinv-recalc-totals').click();
590
                        window.wpiConfirmed = false;
591
                    }
592
                    
593
                    if (msg) {
594
                        alert(msg);
595
                    }
596
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
597
            });
598
        },
599
        remove_item: function() {
600
            // Remove a remove from a purchase
601
            $('#wpinv_items').on('click', '.wpinv-item-remove', function(e) {
602
                var item = $(this).closest('.item');
603
                var count = $(document.body).find('.wpinv-line-items > .item').length;
604
                var qty = parseInt($('.qty', item).data('quantity'));
605
                qty = qty > 0 ? qty : 1;
606
                if (count === 1 && qty == 1) {
607
                    alert(WPInv_Admin.OneItemMin);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
608
                    return false;
609
                }
610
                if (confirm(WPInv_Admin.DeleteInvoiceItem)) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if confirm(WPInv_Admin.DeleteInvoiceItem) is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
611
                    e.preventDefault();
612
                    var metaBox = $('#wpinv_items_wrap');
613
                    var gdTotals = $('.wpinv-totals', metaBox);
614
                    var item_id = item.data('item-id');
615
                    var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
616
                    var index = $(item).index();
617
                    if (!(item_id > 0 && invoice_id > 0)) {
618
                        return false;
619
                    }
620
                    wpinvBlock(metaBox);
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
621
                    var data = {
622
                        action: 'wpinv_remove_invoice_item',
623
                        invoice_id: invoice_id,
624
                        item_id: item_id,
625
                        index: index,
626
                        _nonce: WPInv_Admin.invoice_item_nonce
627
                    };
628
                    $.post(WPInv_Admin.ajax_url, data, function(response) {
629
                        item.remove();
630
                        wpinvUnblock(metaBox);
631
                        if (response && typeof response == 'object') {
632
                            if (response.success === true) {
633
                                WPInv.update_inline_items(response.data, metaBox, gdTotals);
634
                            } else if (response.msg) {
635
                                alert(response.msg);
636
                            }
637
                        }
638
                    });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
639
                }
640
            });
641
        },
642
        add_item: function() {
643
            // Add a New Item from the Add Items to Items Box
644
            $('.wpinv-actions').on('click', '#wpinv-add-item', function(e) {
645
                e.preventDefault();
646
                var metaBox = $('#wpinv_items_wrap');
647
                var gdTotals = $('.wpinv-totals', metaBox);
648
                var item_id = $('#wpinv_invoice_item').val();
649
                var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
650
                if (!(item_id > 0 && invoice_id > 0)) {
651
                    return false;
652
                }
653
                wpinvBlock(metaBox);
654
                var data = {
655
                    action: 'wpinv_add_invoice_item',
656
                    invoice_id: invoice_id,
657
                    item_id: item_id,
658
                    _nonce: WPInv_Admin.invoice_item_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
659
                };
660
                var user_id, country, state;
661
                if (user_id = $('[name="post_author_override"]').val()) {
662
                    data.user_id = user_id;
663
                }
664
                if (parseInt($('#wpinv_new_user').val()) == 1) {
665
                    data.new_user = true;
666
                }
667
                if (country = $('#wpinv-address [name="wpinv_country"]').val()) {
668
                    data.country = country;
669
                }
670
                if (state = $('#wpinv-address [name="wpinv_state"]').val()) {
671
                    data.state = state;
672
                }
673
                $.post(WPInv_Admin.ajax_url, data, function(response) {
674
                    wpinvUnblock(metaBox);
675
                    if (response && typeof response == 'object') {
676
                        if (response.success === true) {
677
                            WPInv.update_inline_items(response.data, metaBox, gdTotals);
678
                        } else if (response.msg) {
679
                            alert(response.msg);
680
                        }
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
681
                    }
682
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
683
            });
684
            $('.wpinv-actions').on('click', '#wpinv-new-item', function(e) {
685
                e.preventDefault();
686
                var $quickAdd = $('#wpinv-quick-add');
687
                if ($quickAdd.is(':visible')) {
688
                    $quickAdd.slideUp('fast');
689
                } else {
690
                    $quickAdd.slideDown('fast');
691
                }
692
                return false;
693
            });
694
            $('#wpinv-quick-add').on('click', '#wpinv-cancel-item', function(e) {
695
                e.preventDefault();
696
                var $quickAdd = $('#wpinv-quick-add');
697
                if ($quickAdd.is(':visible')) {
698
                    $quickAdd.slideUp('fast');
699
                } else {
700
                    $quickAdd.slideDown('fast');
701
                }
702
                return false;
703
            });
704
            $('#wpinv-quick-add').on('click', '#wpinv-save-item', function(e) {
705
                e.preventDefault();
706
                var metaBox = $('#wpinv_items_wrap');
707
                var gdTotals = $('.wpinv-totals', metaBox);
708
                var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
709
                var item_title = $('[name="_wpinv_quick[name]"]', metaBox).val();
710
                var item_price = $('[name="_wpinv_quick[price]"]', metaBox).val();
711
                if (!(invoice_id > 0)) {
712
                    return false;
713
                }
714
                if (!item_title) {
715
                    $('[name="_wpinv_quick[name]"]', metaBox).focus();
716
                    return false;
717
                }
718
                if (item_price === '') {
719
                    $('[name="_wpinv_quick[price]"]', metaBox).focus();
720
                    return false;
721
                }
722
                wpinvBlock(metaBox);
723
                var data = {
724
                    action: 'wpinv_create_invoice_item',
725
                    invoice_id: invoice_id,
726
                    _nonce: WPInv_Admin.invoice_item_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
727
                };
728
                var fields = $('[name^="_wpinv_quick["]');
729
                for (var i in fields) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
730
                    data[fields[i]['name']] = fields[i]['value'];
731
                }
732
                var user_id, country, state;
733
                if (user_id = $('[name="post_author_override"]').val()) {
734
                    data.user_id = user_id;
735
                }
736
                if (parseInt($('#wpinv_new_user').val()) == 1) {
737
                    data.new_user = true;
738
                }
739
                if (country = $('#wpinv-address [name="wpinv_country"]').val()) {
740
                    data.country = country;
741
                }
742
                if (state = $('#wpinv-address [name="wpinv_state"]').val()) {
743
                    data.state = state;
744
                }
745
                $.post(WPInv_Admin.ajax_url, data, function(response) {
746
                    wpinvUnblock(metaBox);
747
                    if (response && typeof response == 'object') {
748
                        if (response.success === true) {
749
                            $('[name="_wpinv_quick[name]"]', metaBox).val('');
750
                            $('[name="_wpinv_quick[price]"]', metaBox).val('');
751
                            WPInv.update_inline_items(response.data, metaBox, gdTotals);
752
                        } else if (response.msg) {
753
                            alert(response.msg);
754
                        }
755
                    }
756
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
757
            });
758
        },
759
        recalculateTotals: function() {
760
            $('.wpinv-actions').on('click', '#wpinv-recalc-totals', function(e) {
761
                e.preventDefault();
762
                var metaBox = $('#wpinv_items_wrap');
763
                var gdTotals = $('.wpinv-totals', metaBox);
764
                var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
765
                if (!invoice_id > 0) {
766
                    return false;
767
                }
768
                if (!parseInt($(document.body).find('.wpinv-line-items > .item').length) > 0) {
769
                    if (!window.wpiConfirmed) {
770
                        alert(WPInv_Admin.emptyInvoice);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
771
                        $('#wpinv_invoice_item').focus();
772
                    }
773
                    return false;
774
                }
775
                if (!window.wpiConfirmed && !window.confirm(WPInv_Admin.confirmCalcTotals)) {
776
                    return false;
777
                }
778
                wpinvBlock(metaBox);
779
                var data = {
780
                    action: 'wpinv_admin_recalculate_totals',
781
                    invoice_id: invoice_id,
782
                    _nonce: WPInv_Admin.wpinv_nonce
783
                };
784
                var user_id, country, state;
785
                if (user_id = $('[name="post_author_override"]').val()) {
786
                    data.user_id = user_id;
787
                }
788
                if (parseInt($('#wpinv_new_user').val()) == 1) {
789
                    data.new_user = true;
790
                }
791
                if (country = $('#wpinv-address [name="wpinv_country"]').val()) {
792
                    data.country = country;
793
                }
794
                if (state = $('#wpinv-address [name="wpinv_state"]').val()) {
795
                    data.state = state;
796
                }
797
                $.post(WPInv_Admin.ajax_url, data, function(response) {
798
                    wpinvUnblock(metaBox);
799
                    if (response && typeof response == 'object') {
800
                        if (response.success === true) {
801
                            WPInv.update_inline_items(response.data, metaBox, gdTotals);
802
                        }
803
                    }
804
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
805
            });
806
        },
807
        update_inline_items: function(data, metaBox, gdTotals) {
808
            if (data.discount > 0) {
809
                data.discountf = '&ndash;' + data.discountf;
810
            }
811
            $('.wpinv-line-items', metaBox).html(data.items);
812
            $('.subtotal .total', gdTotals).html(data.subtotalf);
813
            $('.tax .total', gdTotals).html(data.taxf);
814
            $('.discount .total', gdTotals).html(data.discountf);
815
            $('.total .total', gdTotals).html(data.totalf);
816
            $('#wpinv-details input[name="wpinv_discount"]').val(data.discount);
817
            $('#wpinv-details input[name="wpinv_tax"]').val(data.tax);
818
        },
819
        prices: function() {
820
            var $this = this;
821
            $this.check_recurring('#wpinv_is_recurring');
822
            $(document.body).on('change', '#wpinv_is_recurring', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
823
                $this.check_recurring(this);
824
            });
825
            $(document.body).on('change', '#wpinv_recurring_period', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
826
                $this.recurring_period($(this).val());
827
            });
828
        },
829
        check_recurring: function(el) {
830
            var $obj = $('.wpinv-row-recurring-fields');
831
            this.recurring_period($('#wpinv_recurring_period').val());
832
            if ($(el).is(':checked')) {
833
                $obj.removeClass('wpinv-recurring-n').addClass('wpinv-recurring-y');
834
                $('input', $obj).prop('disabled', false);
835
                $('select', $obj).prop('disabled', false);
836
            } else {
837
                $obj.removeClass('wpinv-recurring-y').addClass('wpinv-recurring-n');
838
                $('input', $obj).prop('disabled', true);
839
                $('select', $obj).prop('disabled', true);
840
            }
841
        },
842
        recurring_period: function(val) {
843
            var txt = '';
844
            if (typeof val != 'undefined') {
845
                txt = $('#wpinv_recurring_period').find('option[value="' + val + '"]').data('text');
846
                txt = txt !== 'undefined' ? txt : '';
847
            }
848
            $('#wpinv_interval_text').text(txt);
849
            this.recurring_interval(val);
850
        },
851
        recurring_interval: function(period) {
852
            var limit;
853
            switch (period) {
854
                case 'W':
855
                    limit = 52;
856
                    break;
857
                case 'M':
858
                    limit = 24;
859
                    break;
860
                case 'Y':
861
                    limit = 5;
862
                    break;
863
                default:
0 ignored issues
show
Coding Style Comprehensibility introduced by
The default case is not the last statement in this switch statement. For the sake of readability, you might want to move it to the end of the statement.
Loading history...
864
                case 'D':
865
                    limit = 90;
866
                    break;
867
            }
868
            var optioins = '';
869
            for (i = 1; i <= limit; i++) {
0 ignored issues
show
Bug introduced by
The variable limit seems to not be initialized for all possible execution paths.
Loading history...
Bug introduced by
The variable i seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.i.
Loading history...
870
                optioins += '<option value="' + i + '">' + i + '</option>';
871
            }
872
            var $el = $('#wpinv_interval');
873
            var val = $el.val();
874
            $el.find('option').remove();
875
            $el.append(optioins);
876
            $el.val(val);
877
            $el.find('option[value="' + val + '"]').attr('selected', 'selected');
878
        },
879
        setup_tools: function() {
880
            $('#wpinv_tools_table').on('click', '.wpinv-tool', function(e) {
881
                var $this = $(this);
882
                e.preventDefault();
883
                var mBox = $this.closest('tr');
884
                if (!confirm(WPInv_Admin.AreYouSure)) {
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
885
                    return false;
886
                }
887
                var tool = $this.data('tool');
888
                $(this).prop('disabled', true);
889
                if (!tool) {
890
                    return false;
891
                }
892
                $('.wpinv-run-' + tool).remove();
893
                if (!mBox.hasClass('wpinv-tool-' + tool)) {
894
                    mBox.addClass('wpinv-tool-' + tool);
895
                }
896
                mBox.addClass('wpinv-tool-active');
897
                mBox.after('<tr class="wpinv-tool-loader wpinv-run-' + tool + '"><td colspan="3"><span class="wpinv-i-loader"><i class="fa fa-spin fa-refresh"></i></span></td></tr>');
898
                var data = {
899
                    action: 'wpinv_run_tool',
900
                    tool: tool,
901
                    _nonce: WPInv_Admin.wpinv_nonce
902
                };
903
                $.post(WPInv_Admin.ajax_url, data, function(res) {
904
                    mBox.removeClass('wpinv-tool-active');
905
                    $this.prop('disabled', false);
906
                    var msg = prem = '';
0 ignored issues
show
Bug introduced by
The variable prem seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.prem.
Loading history...
907
                    if (res && typeof res == 'object') {
908
                        msg = res.data ? res.data.message : '';
909
                        if (res.success === false) {
910
                            prem = '<span class="wpinv-i-check wpinv-i-error"><i class="fa fa-exclamation-circle"></i></span>';
911
                        } else {
912
                            prem = '<span class="wpinv-i-check"><i class="fa fa-check-circle"></i></span>';
913
                        }
914
                    }
915
                    if (msg) {
916
                        $('.wpinv-run-' + tool).addClass('wpinv-tool-done').find('td').html(prem + msg + '<span class="wpinv-i-close"><i class="fa fa-close"></i></span>');
917
                    } else {
918
                        $('.wpinv-run-' + tool).remove();
919
                    }
920
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
921
            });
922
            $('#wpinv_tools_table').on('click', '.wpinv-i-close', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
923
                $(this).closest('tr').fadeOut();
924
            });
925
        }
926
    };
927
    $('.post-type-wpi_invoice form#post #titlediv [name="post_title"]').attr('readonly', true);
928
    $('.post-type-wpi_item.wpi-editable-n form#post').attr('action', 'javascript:void(0)');
929
    $('.post-type-wpi_item.wpi-editable-n #submitdiv #major-publishing-actions').remove();
930
    $('.post-type-wpi_item.wpi-editable-n #submitdiv #misc-publishing-actions a.edit-post-status').remove();
931
    $('.post-type-wpi_item .posts .wpi-editable-n').each(function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
932
        $('.check-column [type="checkbox"]', $(this)).attr('disabled', true);
933
    });
934
    WPInv.init();
935
    var WPInv_Export = {
936
        init: function() {
937
            this.submit();
938
            this.clearMessage();
939
        },
940
        submit: function() {
941
            var $this = this;
942
            $('.wpi-export-form').submit(function(e) {
943
                e.preventDefault();
944
                var $form = $(this);
945
                var submitBtn = $form.find('input[type="submit"]');
946
                if (!submitBtn.attr('disabled')) {
947
                    var data = $form.serialize();
948
                    submitBtn.attr('disabled', true);
949
                    $form.find('.wpi-msg-wrap').remove();
950
                    $form.append('<div class="wpi-msg-wrap"><div class="wpi-progress"><div></div><span>0%</span></div><span class="wpi-export-loader"><i class="fa fa-spin fa-spinner"></i></span></div>');
951
                    // start the process
952
                    $this.step(1, data, $form, $this);
953
                }
954
            });
955
        },
956
        step: function(step, data, $form, $this) {
957
            var message = $form.find('.wpi-msg-wrap');
958
            var post_data = {
959
                action: 'wpinv_ajax_export',
960
                step: step,
961
                data: data,
962
            };
963
            $.ajax({
964
                url: ajaxurl,
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
965
                type: 'POST',
966
                cache: false,
967
                dataType: 'json',
968
                data: post_data,
969
                beforeSend: function(jqXHR, settings) {},
0 ignored issues
show
Unused Code introduced by
The parameter settings is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter jqXHR is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
970
                success: function(res) {
971
                    if (res && typeof res == 'object') {
972
                        if (res.success) {
973
                            if ('done' == res.data.step || res.data.done >= 100) {
974
                                $form.find('input[type="submit"]').removeAttr('disabled');
975
                                $('.wpi-progress > span').text(parseInt(res.data.done) + '%');
976
                                $('.wpi-progress div').animate({
977
                                    width: res.data.done + '%'
978
                                }, 100, function() {});
979
                                if (res.msg) {
980
                                    message.html('<div id="wpi-export-success" class="updated notice is-dismissible"><p>' + msg + '<span class="notice-dismiss"></span></p></div>');
0 ignored issues
show
Bug introduced by
The variable msg seems to be never declared. If this is a global, consider adding a /** global: msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
981
                                }
982
                                if (res.data.file && res.data.file.u) {
983
                                    message.append('<span class="wpi-export-file"><a href="' + res.data.file.u + '" target="_blank"><i class="fa fa-download"></i> ' + res.data.file.u + '</a><span> - ' + res.data.file.s + '<span><span>');
984
                                }
985
                                message.find('.wpi-export-loader').html('<i class="fa fa-check-circle"></i>');
986
                            } else {
987
                                var next = parseInt(res.data.step) > 0 ? parseInt(res.data.step) : 1;
988
                                $('.wpi-progress > span').text(parseInt(res.data.done) + '%');
989
                                $('.wpi-progress div').animate({
990
                                    width: res.data.done + '%'
991
                                }, 100, function() {});
992
                                $this.step(parseInt(next), data, $form, $this);
993
                            }
994
                        } else {
995
                            $form.find('input[type="submit"]').removeAttr('disabled');
996
                            if (res.msg) {
997
                                message.html('<div class="updated error"><p>' + res.msg + '</p></div>');
998
                            }
999
                        }
1000
                    } else {
1001
                        $form.find('input[type="submit"]').removeAttr('disabled');
1002
                        message.html('<div class="updated error">' + res + '</div>');
1003
                    }
1004
                }
1005
            }).fail(function(res) {
1006
                if (window.console && window.console.log) {
1007
                    console.log(res);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
1008
                }
1009
            });
1010
        },
1011
        clearMessage: function() {
1012
            $('body').on('click', '#wpi-export-success .notice-dismiss', function() {
1013
                $(this).closest('#wpi-export-success').parent().slideUp('fast');
1014
            });
1015
        }
1016
    };
1017
    WPInv_Export.init();
1018
1019
});
1020
1021
function wpinvBlock(el, message) {
1022
    message = typeof message != 'undefined' && message !== '' ? message : '';
1023
    el.block({
1024
        message: '<i class="fa fa-spinner fa-pulse fa-2x"></i>' + message,
1025
        overlayCSS: {
1026
            background: '#fff',
1027
            opacity: 0.6
1028
        }
1029
    });
1030
}
1031
1032
function wpinvUnblock(el) {
1033
    el.unblock();
1034
}